package com.excilys.formation.project.repository.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.excilys.formation.project.entities.Client;
import com.excilys.formation.project.repository.ClientDAO;

/**
 * Implémentation de {@link ClientDAO}.
 * 
 * @author excilys
 * 
 */
@Repository
public class ClientDAOImpl implements ClientDAO {
    /**
     * Entity Manager injecté par Spring.
     */
    @PersistenceContext
    private EntityManager em;

    @Override
    public Client getClient(final long id) {
        return em.find(Client.class, id);
    }

    @Override
    public Client getClientByLogin(final String login) {
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Client> criteriaQuery = criteriaBuilder.createQuery(Client.class);
        Root<Client> root = criteriaQuery.from(Client.class);
        criteriaQuery.where(criteriaBuilder.equal(root.get("login"), login));
        return em.createQuery(criteriaQuery).getSingleResult();
    }
}
